package main

import (
	"fmt"
	"zinx-new/ziface"
	"zinx-new/znet"
)

type PingRouter struct {
	// 继承
	znet.BaseRouter
}

func (pr *PingRouter) Handle(request ziface.IRequest) {
	fmt.Println("Call Router Handle")
	fmt.Println("recv from client: msgID=  ", request.GetMsgID(), ", data=", string(request.GetData()))
	// write back
	err := request.GetConnection().SendBuffMsg(0, []byte("ping...ping...pong"))
	if err != nil {
		fmt.Println(err)
	}
}

type HelloZinxRouter struct {
	znet.BaseRouter
}

func (hr *HelloZinxRouter) Handle(request ziface.IRequest) {
	fmt.Println("call hello router")
	fmt.Println("recv from client: msgID= ", request.GetMsgID(), ", data=", string(request.GetData()))
	err := request.GetConnection().SendBuffMsg(1, []byte("hello zinx server"))
	if err != nil {
		fmt.Println(err)
	}
}

func DoConnectionStart(connection ziface.IConnection) {
	println("call before connection")
	connection.SetProperty("Name", "alice")
	connection.SetProperty("Home", "http://alice.com")
	err := connection.SendMsg(2, []byte("do connection begin ..."))
	if err != nil {
		fmt.Println(err)
	}
}

func DoConnectionLost(connection ziface.IConnection) {
	if name, err := connection.GetProperty("Name"); err == nil {
		println("connection property name = ", name)
	}
	if home, err := connection.GetProperty("Home"); err == nil {
		println("connection property home = ", home)
	}
	println("calling do connection lost")

}

func main() {
	s := znet.NewServer()
	s.SetOnConnStart(DoConnectionStart)
	s.SetOnConnStop(DoConnectionLost)
	s.AddRouter(0, &PingRouter{})
	s.AddRouter(1, &HelloZinxRouter{})
	s.Serve()
}
